<!-- 人员花名册弹出框，用来选择人员 -->
<template>
  <a-modal
    width="80%"
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    draggable
    title-align="center"
  >
    <template #title>
      <div>人员花名册</div>
    </template>
    <div class="header" style="margin-bottom: 20px">
      <div class="header-front">
        <a-space>
          <a-input-search
            :style="{ width: '220px' }"
            placeholder="姓名"
            search-button
            @search="onSearch"
            @press-enter="onSearch"
            v-model="nameSearch"
          />
          <a-input-search
            :style="{ width: '220px' }"
            placeholder="手机号"
            search-button
            @search="onSearch"
            @press-enter="onSearch"
            v-model="phoneSearch"
          />
        </a-space>
      </div>
      <div></div>
    </div>

    <div class="main">
      <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
        <a-table-column :width="80">
          <template #title> 序号s </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          title="222"
          v-for="(item, index) in selectedHeader"
          :key="index"
          :data-index="item.ctlCode"
          :width="200"
          :sortable="{
            sortDirections: ['ascend', 'descend']
          }"
        >
          <template
            v-if="showCtlCodeArr.includes(item.ctlCode)"
            #cell="{ record }"
            >{{ item.ctlCode }}
            <ShowInfo :record="record" :ctlCode="item.ctlCode" />
          </template>
        </a-table-column>
        <a-table-column :width="150" fixed="right">
          <template #title>
            <a-tooltip content="是否显示排序">
              <icon-font
                type="icon-filter-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer'
                }"
                @click="isFilter"
              />
            </a-tooltip>
            <a-tooltip content="表头设置">
              <icon-font
                type="icon-setting-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="isHeaderSetting"
              />
            </a-tooltip>
          </template>
          <template #cell="{ record }">
            <a-tooltip content="员工档案">
              <icon-font
                type="icon-details-def"
                :size="26"
                :style="{
                  cursor: 'pointer',
                  marginRight: '10px'
                }"
                @click="goDetail(record.userId)"
              />
            </a-tooltip>

            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="del(record.id)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </template>
        </a-table-column>
      </TableTurn>
    </div>
  </a-modal>
</template>

<script lang="tsx" setup>
import { GetHumanRosterList } from '@/apis/management/human/humanRoster';
import {
  GetHeaderSetting,
  PostHeaderSetting,
  PutHeaderSetting
} from '@/apis/management/base';
import { GetBusinessModalData } from '@/apis/controltotal';
import { getPositionList, getFlatDept } from '@/utils/common';
import { placeSplice } from '@/utils/utils';
import { cloneDeep } from 'lodash';
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框，
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'humanRosterEmit']);

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emit('update:visible', visible);
  }
});

// 表格属性
const args = reactive({
  rowSelection: {
    type: 'radio'
  }
});

const selectedListData = computed(() => tableRef.value.selectedListData);
let forbidList: string[] = []; // 必选的表头
// 新增表头
const addHeader = async () => {
  try {
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
    })) as any;

    let headerListCode: any = [];
    console.log(children, 'children');

    children.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 3,
      headerListCode: headerListCode.join(',')
    });
    getData();
  } catch (error: unknown) {
    console.log(error);
  }
};
let headerSetting = ref<any>([]); // 当前的表头数据

let modalVisiable = ref(false); // 判断是否显示表头
let headerList = ref(); // 接口获取过来的原始表头数据

const placeCtlCode = [
  'C02BE308AEE674E3F95335AED60682954',
  'CF058C6BF648940BA96B49495CC768E20'
]; //户籍所在地、籍贯相关code
// 重组树形数据所需子方法
const controldataTreeFilter = (treeData: any) => {
  const temp = treeData.map((item2: any) => ({
    // 将控件的code赋值对应的value
    [item2.code]:
      // 如果是户籍所在地、籍贯
      placeCtlCode.includes(item2.code) ? placeSplice(item2.value) : item2.value
  }));
  let obj = {};
  temp.forEach((item: any) => {
    obj = { ...obj, ...item };
  });
  return obj;
};

let tableRef = ref();
let nameSearch = ref(''), // 姓名搜索框
  phoneSearch = ref(''); // 手机搜索框
// 获取表格数据
const getTableData = async (pageData?: any) => {
  try {
    let search = 0;
    if (nameSearch.value !== '') search++;
    if (phoneSearch.value !== '') search++;
    const res: any = await GetHumanRosterList({
      ...pageData,
      typeName: '5'
      // name: nameSearch.value,
      // ctlCode: 'C62B8DC31189847E0972B5D8F721404B1',
      // search: search !== 0 ? search + '' : '',
      // phone: phoneSearch.value
    });
    res.content.forEach((item: any) => {
      item.ctlValue.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};
let orginHeaderList = ref([]), // 原始的表头数据
  deptList = ref([]), // 平级部门数据
  positionList = ref([]);

// 获取其他数据
const getData = async () => {
  try {
    const userId = +(localStorage.getItem('userId') as string);
    const [headerSettingRes, deptRes, positionListRes, businessModalDataRes] =
      await Promise.all([
        // 获取人员表头
        GetHeaderSetting({
          ownerFuncType: 3,
          userId
        }),
        // 获取平级的组织数据
        getFlatDept(),
        // 获取所有职位数据
        getPositionList(),
        // 获取控件人员数据
        GetBusinessModalData({
          funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
        })
      ]);
    orginHeaderList.value = headerSettingRes;
    headerSetting.value = [];
    const headerChildren = businessModalDataRes.funcCtlInfos.children;
    headerChildren.forEach((child: any, index: number) => {
      headerSetting.value.push({
        collectionName: child.subDetail.cnName,
        collectionCode: child.subDetail.subCode,
        heads: child.subDetail.subRelDetail.map((subDetail: any) => {
          const isDefault = headerSettingRes.headerListCode.includes(
            subDetail.ctlCode
          );
          return {
            ...subDetail,
            isDefault
          };
        })
      });
    });
    if (headerSettingRes.headerListCode.length < 1) {
      addHeader();
    }
    deptList.value = deptRes;
    positionList.value = positionListRes.content;
    // rosterListNumberRes.forEach((item: any) => {
    //   if (enums[0].includes(item.name)) numberList.list1.push(item);
    //   else if (enums[1].includes(item.name)) numberList.list2.push(item);
    //   else if (enums[2].includes(item.name)) numberList.list3.push(item);
    //   else if (enums[3].includes(item.name)) numberList.list4.push(item);
    // });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'C62B8DC31189847E0972B5D8F721404B1',
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC',
  'CB4163C72FA5E45D38302983E8A66801E',
  'CE183DF5A547A4728A60F9AFDF3C53194',
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'C1F5AA49A78EC4B4FBD487F4D5887E576',
  'C50267C6B8E104B0C91EDD25BCAE35609'
];

// 处理特殊渲染的数据
const ShowInfo = (props: any) => {
  const record = props.record;
  const ctlCode = props.ctlCode;
  switch (ctlCode) {
    // 性别
    case 'CEE710BACA80445DE9A39622878DF04A2':
      return (
        <div>
          {record['CEE710BACA80445DE9A39622878DF04A2'] == 1 ? '男' : '女'}
        </div>
      );
    // 部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return (
        <div>
          {
            deptList.value.find(
              (item: any) =>
                item.id == record['CED44AC9966904CD1AB546D309903727C']
            )?.name
          }
        </div>
      );
    // 职位
    case 'C7341027925C943708F3AEF98703ECC47':
      return (
        <div>
          {
            positionList.value.find(
              (item: any) =>
                item.id == record['C7341027925C943708F3AEF98703ECC47']
            )?.name
          }
        </div>
      );
    // 出生日期、入职时间
    case 'C4869FD6FEC404979A6F73A14DFA07E78' ||
      'CC0D5415792B24BBCAD7DF5AB8A25A0AB':
      return (
        <div>
          {ctlCode == 'C4869FD6FEC404979A6F73A14DFA07E78'
            ? record['C4869FD6FEC404979A6F73A14DFA07E78']?.slice(2, -2)
            : record['CC0D5415792B24BBCAD7DF5AB8A25A0AB']?.slice(2, -2)}
        </div>
      );
    default:
      break;
  }
};

watch(
  () => modalVisible.value,
  (newVal: boolean) => {
    if (newVal) {
      getData();
    }
  }
);

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    modalVisiable.value = !modalVisiable.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    console.log('selectedHeaders', defaultHeaders);
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });

    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将组织名称移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }

  return selectedHeaders;
});

// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    let heads = [...used, ...unused];
    console.log('heads', heads);
    await PutHeaderSetting({
      heads
    });
    headerSetting.value = totalList;
  } catch (error: unknown) {
    console.log(error);
  }
};

const onSearch = () => {
  refresh();
};
const refresh = () => {
  tableRef.value.loadData();
};
// 保存
const handleOk = () => {
  const temp = cloneDeep(
    selectedListData.value[selectedListData.value.length - 1]
  );

  emit('humanRosterEmit', temp);
  // 清空选择器
  tableRef.value.selectedListData = [];
  tableRef.value.selectedList = [];
  modalVisible.value = false;
};

// 取消
const handleCancel = () => {
  // 清空选择器
  tableRef.value.selectedListData = [];
  tableRef.value.selectedList = [];
  modalVisible.value = false;
};
</script>

<style scoped lang="less"></style>
